
extern int Magic = 0;
extern int TrailingStop = 40;


int FixDigits;
double PipPoint;

int init()
{
   AdjDigitsAndPip();
}
int start()
  {
  
   Trailling_Process();
   return(0);
  }
/////////////////////////////////////////////////////////////////
void AdjDigitsAndPip()
{
   if (Digits == 5)
   {
      FixDigits = 4;
      PipPoint = Point*10;
   }
   else if (Digits == 3)
   {
      FixDigits = 2;
      PipPoint = Point*10;
   }
   else
   {
      FixDigits = Digits;
      PipPoint = Point;
   }
}
/////////////////////////////////////////////////////////////////
void Trailling_Process()
{
   int Total;
   Total = OrdersTotal();
   int i,Cmd;
   double Distance,CurrentSL, NewSL;
   double BidValue, AskValue;
   
   
   for (i=0;i<Total;i++)
   {      
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) continue;
      if ((OrderSymbol() == Symbol())&&(OrderMagicNumber()==Magic))
      {
         RefreshRates();
         BidValue = Bid;  
         AskValue = Ask;  
         Cmd = OrderType();
         if(Cmd==OP_BUY)
         {
           if(BidValue-OrderOpenPrice()>PipPoint*TrailingStop)
           {
            if(OrderStopLoss()<BidValue-PipPoint*TrailingStop)
              {
               OrderModify(OrderTicket(),OrderOpenPrice(),BidValue-PipPoint*TrailingStop,OrderTakeProfit(),0,Green);                              
               PlaySound("tick.wav");
              }
           }
         }
         if(Cmd==OP_SELL)
         {
            
          if((OrderOpenPrice()-AskValue)>(PipPoint*TrailingStop))
            {
               
             if((OrderStopLoss()>(AskValue+PipPoint*TrailingStop)) || (OrderStopLoss()==0))
               {
                OrderModify(OrderTicket(),OrderOpenPrice(),AskValue+PipPoint*TrailingStop,OrderTakeProfit(),0,Red);   
                PlaySound("tick.wav");             
               }
            }
         }
      }
   }
}